﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;

namespace Ewell.BizComponent.Reg.UI.VM
{
    public class OutRegVm : INotifyPropertyChanged
    {
        #region 构造函数
        public OutRegVm()
        {
            hasSched = true;
            cashierVisib = Visibility.Collapsed;
        }

        public OutRegVm(OutRegisterRequestVm request) : this()
        {
            this.requestParam = request;
            //querySched.Execute(this);
        }
        #endregion

        /// <summary>
        /// 请求参数
        /// </summary>
        public OutRegisterRequestVm requestParam { get; set; }
        /// <summary>
        /// 当前窗体
        /// </summary>
        public Window localWindow { get; set; }
        /// <summary>
        /// 收银菜单显示
        /// </summary>
        private Visibility _cashierVisib { get; set; }
        public Visibility cashierVisib
        {
            get { return _cashierVisib; }
            set
            {
                if (_cashierVisib != value)
                {
                    _cashierVisib = value;
                    OnPropertyChanged(nameof(cashierVisib));
                }
            }
        }

        /// <summary>
        /// 有无排班
        /// </summary>
        private bool _hasSched;
        public bool hasSched
        {
            get { return _hasSched; }
            set
            {
                if (_hasSched != value)
                {
                    _hasSched = value;
                    OnPropertyChanged(nameof(hasSched));
                }
            }
        }
        /// <summary>
        /// 患者信息
        /// </summary>
        private PatientVm _patient { get; set; }
        public PatientVm patient
        {
            get { return _patient; }
            set
            {
                if (_patient != value)
                {
                    _patient = value;
                    OnPropertyChanged(nameof(patient));
                }
            }
        }
        /// <summary>
        /// 排班信息
        /// </summary>
        private List<ScheduleVm> _scheduleVmList;
        public List<ScheduleVm> scheduleVmList
        {
            get
            {
                return _scheduleVmList;
            }
            set
            {
                if (_scheduleVmList != value)
                {
                    _scheduleVmList = value;
                    OnPropertyChanged(nameof(scheduleVmList));
                }
            }
        }
        /// <summary>
        /// 选中的排班信息
        /// </summary>
        private ScheduleVm _selectedSchedule;
        public ScheduleVm selectedSchedule
        {
            get
            {
                return _selectedSchedule;
            }
            set
            {
                if (_selectedSchedule != value)
                {
                    _selectedSchedule = value;
                    OnPropertyChanged(nameof(selectedSchedule));
                }
            }
        }
        /// <summary>
        /// 支付方式
        /// </summary>
        private List<PayWayVm> _payWayList;
        public List<PayWayVm> payWayList
        {
            get => _payWayList; set
            {
                if (value != _payWayList)
                {
                    _payWayList = value;
                    OnPropertyChanged(nameof(payWayList));
                }
            }
        }
        /// <summary>
        /// 是否免费
        /// </summary>
        private bool _isFree;
        public bool isFree { get => _isFree; set
            {
                if (value != _isFree)
                {
                    _isFree = value;
                    OnPropertyChanged(nameof(isFree));
                }
            } }

        /// <summary>
        /// 结算上下文
        /// </summary>
        //public CashierContext context { get; set; }

        /// <summary>
        /// 预算结果通知
        /// </summary>
        //public event EventHandler<PreChargeResultVm> NoticePreChargeResult;
        /// <summary>
        /// 查询排班信息
        /// </summary>
        //public ICommand querySched => new RelayCommand((object param) =>
        //{
        //    List<ScheduleVm> scheduleList = new List<ScheduleVm>();
        //    if (this.hasSched)
        //    {
        //        List<OutScheduleDTO> outScheduleDTOs = default;
        //        QueryScheduleByExampleV1Request request = new QueryScheduleByExampleV1Request()
        //        {
        //            scheduleDateBegin = DateTime.Today,
        //            scheduleDateEnd = DateTime.Today.AddDays(1).AddSeconds(-1),
        //            encResTypeCodings = new List<string>() { "1" },
        //            bizSourceCoding = requestParam.bizSourceCode=="14"?"4": requestParam.bizSourceCode,
        //            searchAllDayFlag = "1",
        //            providerId = requestParam.docId,
        //            providerTypeCoding = "2"//就诊服务提供者类型代码 1科室2医生
        //        };
        //        ScheduleManageDubboService scheduleManageDubboService = new ScheduleManageDubboService();
        //        var gateWayResult = scheduleManageDubboService.queryScheduleByExampleV1.Post<List<OutScheduleDTO>>(request);
        //        if (!gateWayResult.success) throw new SpeedException("诊间挂号", gateWayResult.message);
        //        outScheduleDTOs = gateWayResult.@object;
        //        //先查医生 医生没查到查科室
        //        if (gateWayResult.@object?.Count <= 0)
        //        {
        //            request.providerId = requestParam.deptId;
        //            request.providerTypeCoding = "1";//就诊服务提供者类型代码 1科室2医生
        //            gateWayResult = scheduleManageDubboService.queryScheduleByExampleV1.Post<List<OutScheduleDTO>>(request);
        //            if (!gateWayResult.success) throw new SpeedException("诊间挂号", gateWayResult.message);
        //            outScheduleDTOs = gateWayResult.@object;
        //        }
        //        foreach (var item in outScheduleDTOs)
        //        {
        //            ScheduleVm schedule = new ScheduleVm();
        //            schedule.encScheduleId = item.encScheduleId;
        //            schedule.msId = item.msId;
        //            schedule.msName = item.msName;
        //            schedule.registrationTypeId = item.registrationTypeId;
        //            schedule.registrationTypeName = item.registrationTypeName;
        //            schedule.regCategoryId = item.regCategoryId;
        //            schedule.quantity = item.quantity;
        //            schedule.quantityUsed = item.quantityUsed;
        //            schedule.quantityRemain = item.quantityRemain;
        //            schedule.regAmount = item.regAmount;
        //            schedule.noonTypeId = item.noonTypeId;
        //            schedule.noonTypeCoding = item.noonTypeCoding;
        //            schedule.noonTypeName = item.noonTypeName;
        //            schedule.beginTime = item.beginTime;
        //            schedule.endTime = item.endTime;
        //            schedule.providerId = item.providerId;
        //            schedule.providerTypeCoding = item.providerTypeCoding;
        //            schedule.docId = item.providerTypeCoding == "2" ? item.providerId : "";
        //            schedule.docCode = item.providerTypeCoding == "2" ? requestParam.docCode : "";
        //            schedule.docName = item.providerTypeCoding == "2" ? item.providerName : "";
        //            schedule.deptId = item.providerTypeCoding == "1" ? item.providerId : requestParam.deptId;
        //            schedule.deptCode = item.providerTypeCoding == "1" ? requestParam.deptCode : "";
        //            schedule.deptName = item.providerTypeCoding == "1" ? item.providerName : requestParam.deptName;
        //            List<EsSlotSettingVm> esSlotList = new List<EsSlotSettingVm>();
        //            if(item.esSlotSettingList!=null)
        //            {
        //                foreach (var esSlot in item.esSlotSettingList)
        //                {
        //                    EsSlotSettingVm esSlotSetting = new EsSlotSettingVm()
        //                    {
        //                        esSlotSettingId = esSlot.esSlotSettingId,
        //                        quantity = esSlot.quantity,
        //                        quantityPlaned = esSlot.quantityPlaned,
        //                        quantityRemain = esSlot.quantityRemain,
        //                        quantityUsed = esSlot.quantityUsed,
        //                        beginAtTime = esSlot.beginAtTime,
        //                        endAtTime = esSlot.endAtTime,
        //                    };
        //                    esSlotList.Add(esSlotSetting);
        //                }
        //            }
        //            schedule.esSlotSettingList = esSlotList;
        //            scheduleList.Add(schedule);
        //        }
        //    }
        //    else if (!this.hasSched)
        //    {
        //        List<QueryESResponse> queryESResponses = default;
        //        QueryESRequest request = new QueryESRequest()
        //        {
        //            enabledFlag = "1",
        //            providerId = requestParam.docId,
        //            providerTypeCoding = "2"//就诊服务提供者类型代码 1科室2医生
        //        };
        //        EncounterServiceDubboService encounterServiceDubboService = new EncounterServiceDubboService();
        //        var gateWayResult = encounterServiceDubboService.queryESByExample.Post<List<QueryESResponse>>(request);
        //        if (!gateWayResult.success) throw new SpeedException("诊间挂号", gateWayResult.message);
        //        queryESResponses = gateWayResult.@object;

        //        //先查医生 医生没查到查科室
        //        if (gateWayResult.@object?.Count <= 0)
        //        {
        //            request.providerId = requestParam.deptId;
        //            request.providerTypeCoding = "1";//就诊服务提供者类型代码 1科室2医生
        //            gateWayResult = encounterServiceDubboService.queryESByExample.Post<List<QueryESResponse>>(request);
        //            if (!gateWayResult.success) throw new SpeedException("诊间挂号", gateWayResult.message);
        //            queryESResponses = gateWayResult.@object;
        //        }

        //        foreach (var item in queryESResponses)
        //        {
        //            foreach (var esProvider in item.esProviderList)
        //            {
        //                foreach (var esXRegType in esProvider.esXRegTypeList)
        //                {
        //                    ScheduleVm schedule = new ScheduleVm();
        //                    schedule.msId = item.msId;
        //                    schedule.msName = item.msName;
        //                    schedule.registrationTypeId = esXRegType.regTypeId;
        //                    schedule.registrationTypeName = esXRegType.regTypeName;
        //                    schedule.regCategoryId = esXRegType.regCategory;
        //                    schedule.regAmount = esXRegType.regAmount;
        //                    schedule.providerId = esProvider.esProviderId;
        //                    schedule.providerTypeCoding = esProvider.esProviderTypeCoding;
        //                    schedule.docId = esProvider.esProviderTypeCoding == "2" ? esProvider.esProviderId : "";
        //                    schedule.docCode = esProvider.esProviderTypeCoding == "2" ? requestParam.docCode : "";
        //                    schedule.docName = esProvider.esProviderTypeCoding == "2" ? esProvider.esProviderName : "";
        //                    schedule.deptId = esProvider.esProviderTypeCoding == "1" ? esProvider.esProviderId : "";
        //                    schedule.deptCode = esProvider.esProviderTypeCoding == "1" ? requestParam.deptCode : "";
        //                    schedule.deptName = esProvider.esProviderTypeCoding == "1" ? esProvider.esProviderName : "";
        //                    List<RegNoonTypeVm> regNoonTypes = new List<RegNoonTypeVm>();
        //                    if(esXRegType.regNoonTypeList!=null)
        //                    {
        //                        foreach (var regNoonType in esXRegType.regNoonTypeList)
        //                        {
        //                            RegNoonTypeVm regNoonTypeVm = new RegNoonTypeVm();
        //                            regNoonTypeVm.regNoonTypeId = regNoonType.regNoonTypeId;
        //                            regNoonTypeVm.beginAtTime = regNoonType.beginAtTime;
        //                            regNoonTypeVm.endAtTime = regNoonType.endAtTime;
        //                            regNoonTypes.Add(regNoonTypeVm);
        //                        }
        //                    }
        //                    schedule.regNoonTypeList = regNoonTypes;
        //                    scheduleList.Add(schedule);
        //                }
        //            }
        //        }
        //    }
        //    scheduleVmList = scheduleList.OrderBy(o=>o.beginTime).ToList();
        //});

        ///// <summary>
        ///// 挂号事件
        ///// </summary>
        //public ICommand register => new RelayCommand((object param) =>
        //{
        //    //加号标志
        //    string encResAddFlag = "0";
        //    if (patient == null || string.IsNullOrWhiteSpace(patient.patientId))
        //    {
        //        MessageBox.Show("没有患者信息,请建档后重试!");
        //        return;
        //    }
        //    if (param == null)
        //    {
        //        MessageBox.Show("未选择挂号内容！请选择挂号内容！");
        //        return;
        //    }
        //    //预算结果
        //    PreChargeResultVm preChargeResult = new PreChargeResultVm()
        //    {
        //        success = false
        //    };
        //    ScheduleVm schedule = param as ScheduleVm;
        //    //参数校验
        //    var scheduleSlotId = schedule.esSlotSettingList?.OrderBy(o=>o.endAtTime).FirstOrDefault(f => f.endAtTime >= DateTime.Now)?.esSlotSettingId;
        //    //schedule.encScheduleId为空是不限号
        //    //schedule.encScheduleId不为空是限号，限号且无排班报错
        //    if (hasSched&& string.IsNullOrWhiteSpace(scheduleSlotId)&&!string.IsNullOrWhiteSpace(schedule.encScheduleId))
        //    {
        //        ConfigQueryRequest request = new ConfigQueryRequest()
        //        {
        //            codes = new List<string>() { "3059" }
        //        };
        //        ConfigAllDubboService configAllDubboService = new ConfigAllDubboService();
        //        var gateWayConfig = configAllDubboService.queryPageConfig.Post<List<ConfigResponse>>(request);
        //        if (!gateWayConfig.success) throw new SpeedException("接口代理", gateWayConfig.message);
        //        if (gateWayConfig.@object != null && gateWayConfig.@object.All(c => c.value.Trim() != "1"))
        //        {
        //            var messageBoxResult=MessageBox.Show($"【{schedule.docName+ schedule.deptName}】出诊的【{schedule.msName}】已无可用号源，是否加号","警告!",MessageBoxButton.YesNo,MessageBoxImage.Question);
        //            if(messageBoxResult== MessageBoxResult.Yes)
        //            {
        //                encResAddFlag = "1";
        //                scheduleSlotId= schedule.esSlotSettingList?.OrderByDescending(o => o.endAtTime).FirstOrDefault()?.esSlotSettingId;
        //            }
        //        }
        //        else
        //        {
        //            MessageBox.Show("号源没有当前时段可用的排班!");
        //            return;
        //        }
        //    }
        //    var regNoonType = schedule.regNoonTypeList?.OrderBy(o=>o.endAtTime).FirstOrDefault(f => f.endAtTime >= DateTime.Now);
        //    //if(!hasSched&& regNoonType == null)
        //    //{
        //    //    MessageBox.Show("出班午别列表不包含当前时段!");
        //    //    return;
        //    //}

        //    //挂号预算
        //    OutPreRegisterRequest preRegisterDto = new OutPreRegisterRequest()
        //    {
        //        bizSourceCoding = requestParam.bizSourceCode,
        //        patient = new PatientDto()
        //        {
        //            insurTypeId = patient.patientTypeNo,
        //            patientId = patient.patientId,
        //            patientName = patient.name,
        //        },
        //        preRegist = new PreRegistDto()
        //        {
        //            visitTypeCoding = "1", //1现场就诊 2线上就诊
        //            outEncounterList = new List<ScheduleDto>()
        //            {
        //                new ScheduleDto()
        //                {
        //                    msId=schedule.msId,
        //                    paymentTypeCoding=isFree?"2":"1",//1正常收费 2全免费
        //                    scheduleId=schedule.encScheduleId,
        //                    scheduleSlotId=scheduleSlotId,//排班时段标识 有排班必传
        //                    providerId=schedule.providerId,
        //                    providerTypeCoding=schedule.providerTypeCoding,
        //                    regTypeId=schedule.registrationTypeId,
        //                    regCategoryId=schedule.regCategoryId,
        //                    attendAtBegin=DateTime.Today,
        //                    attendAtEnd=DateTime.Today.AddDays(1).AddSeconds(-1),
        //                    encResAddFlag=encResAddFlag,
        //                }
        //            }
        //        }
        //    };
        //    OutRegisterServer outRegisterServer = new OutRegisterServer();
        //    OutSettlementServer outSettlementServer = new OutSettlementServer();
        //    OutPreRegisterResponse preSettlementResult = default;
        //    try
        //    {
        //        preSettlementResult = outRegisterServer.PreRegister(preRegisterDto);
        //    }
        //    catch (SpeedException ex)
        //    {
        //        MessageBox.Show($"预算失败!,{ex.Message}");
        //        return;
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show($"预算失败!,{ex.Message}");
        //        return;
        //    }

        //    try
        //    {
        //        OutPreSettlementRequest outPreSettlementRequest = new OutPreSettlementRequest()
        //        {
        //            bizSourceCoding = requestParam.bizSourceCode,
        //            menuId = requestParam.menuId,
        //            preSettlementList = preSettlementResult.preSettlementList,
        //            patient = new PatientDto()
        //            {
        //                insurTypeId = patient.patientTypeNo,
        //                patientId = patient.patientId,
        //                patientName = patient.name,
        //            },
        //            encounter=new EncounterDto()
        //            {
        //                encounterId= long.Parse(preSettlementResult.preSettlementList.FirstOrDefault().outEncounterId),
        //            },
        //            settlementTypeCode="1"
        //        };
        //        List<Charge.UI.VM.PayWayVm> payWayVms = new List<Charge.UI.VM.PayWayVm>();
        //        foreach (var item in this.payWayList)
        //        {
        //            payWayVms.Add(item.CopyProperties<Charge.UI.VM.PayWayVm>());
        //        }
        //        CashierMainVm cashierMainVm = new CashierMainVm(this.patient.CopyProperties<Charge.UI.VM.PatientVm>(), payWayVms, outPreSettlementRequest);
        //        CashierMainFrm cashierMainFrm = new CashierMainFrm(cashierMainVm);
        //        cashierMainVm.localWindow= cashierMainFrm;
        //        bool? result=cashierMainFrm.ShowDialog();
        //        if (result != true)
        //        {
        //            outRegisterServer.PreRegistCancel(new List<string>() { preSettlementResult.preSettlementList.FirstOrDefault().outEncounterId });
        //            return;
        //        }

        //        //PreSettlementResponse outPreSettlementResponse = outSettlementServer.PreSettlement(outPreSettlementRequest);
        //        this.context = cashierMainVm.context;
        //        //preChargeResult.success = true;
        //        //preChargeResult.settlementId = cashierMainVm.context.outPreSettlementResponse.settlementId;
        //        //preChargeResult.amount = cashierMainVm.context.outPreSettlementResponse.amount;
        //        //preChargeResult.discountAmount = cashierMainVm.context.outPreSettlementResponse.discountAmount;
        //        //preChargeResult.encounterId = cashierMainVm.context.outPreSettlementRequest.encounter.encounterId;
        //        //preChargeResult.settlementTypeCode = cashierMainVm.context.outPreSettlementResponse.settlementTypeCode;
        //        this.localWindow.DialogResult = true;
        //        this.localWindow.Close();
        //    }
        //    catch (SpeedException ex)
        //    {
        //        MessageBox.Show($"结算失败!,{ex.Message}");
        //        outRegisterServer.PreRegistCancel(preSettlementResult.preSettlementList.Select(s => s.outEncounterId).ToList());
        //        return;
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show($"结算失败!,{ex.Message}");
        //        outRegisterServer.PreRegistCancel(preSettlementResult.preSettlementList.Select(s => s.outEncounterId).ToList());
        //        return;
        //    }
        //    //NoticePreChargeResult.Invoke(this, preChargeResult);
        //});

        ///// <summary>
        ///// 取消事件
        ///// </summary>
        //public ICommand cancel => new RelayCommand((object param) =>
        //{
        //    if (localWindow != null)
        //    {
        //        try
        //        {
        //            localWindow.DialogResult = false;
        //        }
        //        catch (Exception)
        //        {
        //        }
        //    }
        //    localWindow?.Close();
        //});

        //public ICommand createPat => new RelayCommand(param =>
        //{
        //    PersonCreateVm personCreateVm = new PersonCreateVm()
        //    {
        //        menuId=requestParam.menuId,
        //        bizSourceNo= requestParam.bizSourceNo,
        //    };
        //    PersonCreateFrm personCreateFrm = new PersonCreateFrm(personCreateVm);
        //    bool? diagResult = personCreateFrm.ShowDialog();
        //    if (diagResult??false)
        //    {
        //        this.patient = personCreateFrm.vm.resultPatient;
        //    }
        //});



        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
